package com.ysd.service.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Component
@Slf4j
public class WeChatUtil {

    /**
     * 小程序登录授权
     */
    public String getAccessTokenAndOpenId(String appId, String appSecret, String code) {
        log.info("appid = " + appId + ",appsecret = " + appSecret + ",code = " + code);
        // 构造请求URL
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId +
                "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";

        // 创建URL对象
        URL urlObj = null;
        try {
            urlObj = new URL(url);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);

            // 获取响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            String result = response.toString();
            log.info("微信授权登录响应数据===", result);

            // 解析返回的JSON数据
            JSONObject jsonResponse = JSONObject.parseObject(result);

            // 获取access_token和openid
            String accessToken = jsonResponse.getString("access_token");
            String openId = jsonResponse.getString("openid");

            // 返回access_token和openid
            return result;
        } catch (IOException e) {
            log.error("wxLogin 获取sesstionkey失败", e);
            e.printStackTrace();
        }
        return "";
    }


}
